package com.freedom.monitor.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.freedom.monitor.myeye.config.service.LoginUser;
import com.freedom.monitor.myeye.config.service.UserConfigService;
import com.freedom.monitor.myeye.config.service.UserResult;
import com.freedom.monitor.utils.ConstantUtils;
import com.freedom.monitor.utils.CookieUtils;
import com.freedom.monitor.utils.ExclusionStrategyUtils;
import com.freedom.monitor.utils.StringUtils;
import com.freedom.rpc.thrift.common.utils.Logger;
import com.freedom.rpc.thrift.common.utils.SocketUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

@Controller
@RequestMapping(value = "/user")
public class UserController {// 用户登录
	//
	private static final Logger logger = Logger.getLogger(UserController.class);

	// 删除cookie--->http://www.jb51.net/article/46882.htm
	@RequestMapping(value = "/logout", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView logout(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		logger.debug("log out invoked...");
		// 1)取消cookie
		CookieUtils.deleteCookie(response, ConstantUtils.COOKIE_USER_ID);
		CookieUtils.deleteCookie(response, ConstantUtils.COOKIE_TOKEN);
		// 2)调到index.jsp上
		return new ModelAndView("index", model);

	}

	@RequestMapping(value = "/login", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView login(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		logger.debug("one user log in...");
		// 1)获取证所有参数存在且合法
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		//
		if (false == StringUtils.valid(username, password)) {
			model.addAttribute("error", "invalid request parameter...");
			return new ModelAndView("index", model);
		}
		username = username.trim();
		password = password.trim();
		logger.debug("username:" + username + " password:" + password);
		// 2)尝试调用远程服务
		LoginUser loginUser = null;
		try {
			logger.debug("try to get UserService.Client userServiceClient");
			UserConfigService.Client userServiceClient = (UserConfigService.Client) SocketUtils
					.getSyncAopObject(UserConfigService.Client.class);
			logger.debug("succeed to get UserService.Client userServiceClient");
			loginUser = userServiceClient.login(username, password);
		} catch (Exception e) {
			logger.error("set error attribute succeed...due to " + e.toString());
			loginUser = null;
		}
		logger.debug("now we get loginUser,ok or not ?");
		// 3)远程服务调用成功,但是不知道结果如何，所以要判断
		if (null == loginUser) {// 内部异常
			logger.error("internal server error,please retry...");
			model.addAttribute("error", "internal server error,please retry...");
			return new ModelAndView("index", model);
		}
		// 4)没有这个人
		if (false == loginUser.succeed) {
			logger.warn(loginUser.getErrorMsg());
			model.addAttribute("error", loginUser.getErrorMsg());
			return new ModelAndView("index", model);
		}
		// 5)很好，调用成功，返回了一个正确的token,那么就生成cookie
		logger.debug("login succeed...");
		{
			CookieUtils.addCookie(response, ConstantUtils.COOKIE_USER_ID, "" + loginUser.getUserId());
			CookieUtils.addCookie(response, ConstantUtils.COOKIE_TOKEN, loginUser.getToken());
			logger.debug("add 2 cookie succeed...");
		}
		// 6)测试用
		model.clear();
		logger.debug("current user role ---> " + loginUser.getRole());
		model.addAttribute("role", new Integer(loginUser.getRole()));
		return new ModelAndView("main", model);
	}

	// 首页进来
	@RequestMapping(value = "/index", method = { RequestMethod.GET })
	public ModelAndView index(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		logger.debug("index for user...");
		return new ModelAndView("user/index", model);// 返回user/user.jsp
	}

	// 查询所有用户
	@RequestMapping(value = "/query", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	@ResponseBody
	public String query(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		logger.info("UserController.query invoked...");
		// 1)先获取type参数
		String page = request.getParameter("page");
		String rows = request.getParameter("rows");
		if (false == StringUtils.valid(page, rows)) {
			page = "1";
			rows = "10";
		}
		int intPage = Integer.parseInt(page.trim());
		int intRows = Integer.parseInt(rows.trim());
		logger.debug("received --->" + "page->" + page + " rows:" + rows);
		// 2)尝试获取远程服务结果
		UserResult result = new UserResult();
		try {
			logger.debug("try to get UserService.Client userServiceClient");
			UserConfigService.Client configServiceClient = (UserConfigService.Client) SocketUtils
					.getSyncAopObject(UserConfigService.Client.class);
			logger.debug("succeed to get UserService.Client userServiceClient");
			result = configServiceClient.queryUser(intPage, intRows);
			// 拿到了结果
			if (true == result.isSucceed() && result.getUserListSize() >= 0) {
				// 正确且有数据
				Gson gson = new GsonBuilder().setExclusionStrategies(ExclusionStrategyUtils.getInstance()).create();
				String str = "" + "{\"total\":" + result.getTotal() + ","//
						+ "\"rows\":" + gson.toJson(result.getUserList())//
						+ "}";
				logger.debug("" + str);
				return str;
			}
			throw new Exception("user result is not valid");
		} catch (Exception e) {// 返回空数据
			return "{\"total\":0,\"rows\":[]}";
		}
	}

	// 删除
	@RequestMapping(value = "/del", method = { RequestMethod.POST }, produces = "application/json; charset=utf-8")
	@ResponseBody
	public String delete(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		logger.info("UserController.delete invoked...");
		boolean result = false;
		try {
			// 1)先获取id
			String userId = request.getParameter("userid");
			if (false == StringUtils.valid(userId)) {
				throw new Exception("invalid userId--->" + userId);
			}
			logger.debug("received to be delete user id --->" + userId);
			// 2)尝试获取远程服务结果
			logger.debug("try to get ConfigService.Client configServiceClient");
			UserConfigService.Client configServiceClient = (UserConfigService.Client) SocketUtils
					.getSyncAopObject(UserConfigService.Client.class);
			logger.debug("succeed to get ConfigService.Client configServiceClient");
			result = configServiceClient.deleteUser(userId);
			// 拿到了结果
			if (true == result) {
				// 正确且有数据
				return "{\"success\":true}";

			} else {
				return "{\"success\":false}";
			}
		} catch (Exception e) {// 返回空数据
			return "{\"success\":false,\"errorMsg\":\"" + e.toString() + "\"}";
		}
	}

	// 新增
	@RequestMapping(value = "/addOrUpdate", method = {
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	@ResponseBody
	public String addOrUpdate(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		logger.debug("User Controller.add() invoked...");
		try {
			// 1)获取参数
			String userid = request.getParameter("userid");
			logger.debug("userid---" + userid);
			String username = request.getParameter("username");
			String name = request.getParameter("name");
			String pwd = request.getParameter("pwd");
			String role = request.getParameter("role");
			if (false == StringUtils.valid(username, name, pwd, role)) {
				throw new Exception("invalid parameter...");
			}
			// 2)调用远程的程序
			logger.debug("try to get UserService.Client userServiceClient");
			UserConfigService.Client configServiceClient = (UserConfigService.Client) SocketUtils
					.getSyncAopObject(UserConfigService.Client.class);
			logger.debug("succeed to get UserService.Client userServiceClient");
			boolean result = false;
			if (null != userid && userid.trim().length() > 0) {
				logger.debug("action->edit");
				result = configServiceClient.editUser(username, name, pwd, Integer.parseInt(role), userid);
			} else {
				logger.debug("action->add");
				result = configServiceClient.addUser(username, name, pwd, Integer.parseInt(role));
			}
			// 拿到了结果
			if (true == result) {
				// 正确且有数据
				return "{\"success\":true}";

			} else {
				return "{\"success\":false}";
			}
		} catch (Exception e) {
			return "{\"success\":false,\"errorMsg\":\"" + e.toString() + "\"}";
		}
	}

}
